<?php
class system_db_select {
	
	const DISTINCT = 'distinct';
	const COLUMNS = 'columns';
	const FROM = 'from';
	const UNION = 'union';
	const WHERE = 'where';
	const GROUP = 'group';
	const HAVING = 'having';
	const ORDER = 'order';
	const LIMIT_COUNT = 'limitcount';
	const LIMIT_OFFSET = 'limitoffset';
	const FOR_UPDATE = 'forupdate';
	
	const INNER_JOIN = 'inner join';
	const LEFT_JOIN = 'left join';
	const RIGHT_JOIN = 'right join';
	const FULL_JOIN = 'full join';
	const CROSS_JOIN = 'cross join';
	const NATURAL_JOIN = 'natural join';
	
	const SQL_WILDCARD = '*';
	const SQL_SELECT = 'SELECT';
	const SQL_UNION = 'UNION';
	const SQL_UNION_ALL = 'UNION ALL';
	const SQL_FROM = 'FROM';
	const SQL_WHERE = 'WHERE';
	const SQL_DISTINCT = 'DISTINCT';
	const SQL_GROUP_BY = 'GROUP BY';
	const SQL_ORDER_BY = 'ORDER BY';
	const SQL_HAVING = 'HAVING';
	const SQL_FOR_UPDATE = 'FOR UPDATE';
	const SQL_AND = 'AND';
	const SQL_AS = 'AS';
	const SQL_OR = 'OR';
	const SQL_ON = 'ON';
	const SQL_ASC = 'ASC';
	const SQL_DESC = 'DESC';
	
	protected $_bind = array();
	protected $_adapter;
	
	/**
	 * The initial values for the $_parts array.
	 * NOTE: It is important for the 'FOR_UPDATE' part to be last to ensure
	 * meximum compatibility with database adapters.
	 *
	 * @var array
	 */
	protected static $_partsInit = array(self::DISTINCT => false, self::COLUMNS => array(), self::UNION => array(), self::FROM => array(), self::WHERE => array(), self::GROUP => array(), self::HAVING => array(), self::ORDER => array(), self::LIMIT_COUNT => null, self::LIMIT_OFFSET => null, self::FOR_UPDATE => false);
	
	/**
	 * Specify legal join types.
	 *
	 * @var array
	 */
	protected static $_joinTypes = array(self::INNER_JOIN, self::LEFT_JOIN, self::RIGHT_JOIN, self::FULL_JOIN, self::CROSS_JOIN, self::NATURAL_JOIN);
	
	/**
	 * Specify legal union types.
	 *
	 * @var array
	 */
	protected static $_unionTypes = array(self::SQL_UNION, self::SQL_UNION_ALL);
	
	/**
	 * The component parts of a SELECT statement.
	 * Initialized to the $_partsInit array in the constructor.
	 *
	 * @var array
	 */
	protected $_parts = array();
	
	/**
	 * Tracks which columns are being select from each table and join.
	 *
	 * @var array
	 */
	protected $_tableCols = array();
	
	/**
	 * Class constructor
	 *
	 * @param Zend_Db_Adapter_Abstract $adapter
	 */
	public function __construct(system_db_adapter_abstract $adapter = null) {
		if(null===$adapter) {
			$adapter = system_db::getAdapter();
		}
		$this->_adapter = $adapter;
		$this->_parts = self::$_partsInit;
		$this->init();
	}
	
	protected function init() {
	}
	
	/**
	 * Get bind variables
	 *
	 * @return array
	 */
	public function getBind() {
		return $this->_bind;
	}
	
	/**
	 * Set bind variables
	 *
	 * @param mixed $bind
	 * @return Zend_Db_Select
	 */
	public function bind($bind) {
		$this->_bind = $bind;
		
		return $this;
	}
	
	/**
	 * Makes the query SELECT DISTINCT.
	 *
	 * @param bool $flag Whether or not the SELECT is DISTINCT (default true).
	 * @return $this
	 */
	public function distinct($flag = true) {
		$this->_parts[self::DISTINCT] = (bool) $flag;
		return $this;
	}
	
	public function from($name, $cols = '*', $schema = null) {
		return $this->_join(self::FROM, $name, null, $cols, $schema);
	}
	
	public function columns($cols = '*', $correlationName = null) {
		if($correlationName===null&&count($this->_parts[self::FROM])) {
			$correlationNameKeys = array_keys($this->_parts[self::FROM]);
			$correlationName = current($correlationNameKeys);
		}
		
		if(!array_key_exists($correlationName, $this->_parts[self::FROM])) {
			throw new system_db_select_exception("No table has been specified for the FROM clause");
		}
		
		$this->_tableCols($correlationName, $cols);
		
		return $this;
	}
	
	public function union($select = array(), $type = self::SQL_UNION) {
		if(!is_array($select)) {
			throw new system_db_select_exception("union() only accepts an array of system_db_select instances of sql query strings.");
		}
		
		if(!in_array($type, self::$_unionTypes)) {
			throw new system_db_select_exception("Invalid union type '{$type}'");
		}
		
		foreach($select as $target) {
			$this->_parts[self::UNION][] = array($target, $type);
		}
		
		return $this;
	}
	
	protected function _checkName($name) {
		if(is_string($name)) {
			return system_db_table::getTablePrefix().$name;
		} elseif($name instanceof system_db_table_abstract) {
			return $name->getFullName();
		} else {
			throw new system_db_select_exception('The table name error');
		}
	}
	
	public function join($name, $cond, $cols = self::SQL_WILDCARD, $schema = null) {
		return $this->joinInner($name, $cond, $cols, $schema);
	}
	
	public function joinInner($name, $cond, $cols = self::SQL_WILDCARD, $schema = null) {
		return $this->_join(self::INNER_JOIN, $name, $cond, $cols, $schema);
	}
	
	public function joinLeft($name, $cond, $cols = self::SQL_WILDCARD, $schema = null) {
		return $this->_join(self::LEFT_JOIN, $name, $cond, $cols, $schema);
	}
	
	public function joinRight($name, $cond, $cols = self::SQL_WILDCARD, $schema = null) {
		return $this->_join(self::RIGHT_JOIN, $name, $cond, $cols, $schema);
	}
	
	public function joinFull($name, $cond, $cols = self::SQL_WILDCARD, $schema = null) {
		return $this->_join(self::FULL_JOIN, $name, $cond, $cols, $schema);
	}
	
	public function joinCross($name, $cols = self::SQL_WILDCARD, $schema = null) {
		return $this->_join(self::CROSS_JOIN, $name, null, $cols, $schema);
	}
	
	public function joinNatural($name, $cols = self::SQL_WILDCARD, $schema = null) {
		return $this->_join(self::NATURAL_JOIN, $name, null, $cols, $schema);
	}
	
	public function where($cond, $value = null, $type = null) {
		$this->_parts[self::WHERE][] = $this->_where($cond, $value, $type, true);
		
		return $this;
	}
	
	public function orWhere($cond, $value = null, $type = null) {
		$this->_parts[self::WHERE][] = $this->_where($cond, $value, $type, false);
		
		return $this;
	}
	
	public function group($spec) {
		if(!is_array($spec)) {
			$spec = array($spec);
		}
		
		foreach($spec as $val) {
			if(preg_match('/\(.*\)/', (string) $val)) {
				$val = new system_db_expr($val);
			}
			$this->_parts[self::GROUP][] = $val;
		}
		
		return $this;
	}
	
	public function having($cond) {
		if(func_num_args()>1) {
			$val = func_get_arg(1);
			$cond = $this->_adapter->quoteInto($cond, $val);
		}
		
		if($this->_parts[self::HAVING]) {
			$this->_parts[self::HAVING][] = self::SQL_AND." ($cond)";
		} else {
			$this->_parts[self::HAVING][] = "($cond)";
		}
		
		return $this;
	}
	
	public function orHaving($cond) {
		if(func_num_args()>1) {
			$val = func_get_arg(1);
			$cond = $this->_adapter->quoteInto($cond, $val);
		}
		
		if($this->_parts[self::HAVING]) {
			$this->_parts[self::HAVING][] = self::SQL_OR." ($cond)";
		} else {
			$this->_parts[self::HAVING][] = "($cond)";
		}
		
		return $this;
	}
	
	public function order($spec) {
		if(!is_array($spec)) {
			$spec = array($spec);
		}
		
		// force 'ASC' or 'DESC' on each order spec, default is ASC.
		foreach($spec as $val) {
			if($val instanceof system_db_expr) {
				$expr = $val->__toString();
				if(empty($expr)) {
					continue;
				}
				$this->_parts[self::ORDER][] = $val;
			} else {
				if(empty($val)) {
					continue;
				}
				$direction = self::SQL_ASC;
				if(preg_match('/(.*\W)('.self::SQL_ASC.'|'.self::SQL_DESC.')\b/si', $val, $matches)) {
					$val = trim($matches[1]);
					$direction = $matches[2];
				}
				if(preg_match('/\(.*\)/', $val)) {
					$val = new system_db_expr($val);
				}
				$this->_parts[self::ORDER][] = array($val, $direction);
			}
		}
		
		return $this;
	}
	
	public function limit($count = null, $offset = null) {
		$this->_parts[self::LIMIT_COUNT] = (int) $count;
		$this->_parts[self::LIMIT_OFFSET] = (int) $offset;
		return $this;
	}
	
	public function limitPage($page, $rowCount) {
		$page = ($page>0) ? $page : 1;
		$rowCount = ($rowCount>0) ? $rowCount : 1;
		return $this->limit((int) $rowCount, (int) $rowCount*($page-1));
	}
	
	public function forUpdate($flag = true) {
		$this->_parts[self::FOR_UPDATE] = (bool) $flag;
		return $this;
	}
	
	public function getPart($part) {
		$part = strtolower($part);
		if(!array_key_exists($part, $this->_parts)) {
			throw new system_db_select_exception("Invalid Select part '$part'");
		}
		return $this->_parts[$part];
	}
	
	public function query($fetchMode = null, $bind = array()) {
		if(!empty($bind)) {
			$this->bind($bind);
		}
		
		$stmt = $this->_adapter->query($this);
		if($fetchMode==null) {
			$fetchMode = $this->_adapter->getFetchMode();
		}
		$stmt->setFetchMode($fetchMode);
		return $stmt;
	}
	
	public function assemble() {
		$sql = self::SQL_SELECT;
		foreach(array_keys(self::$_partsInit) as $part) {
			$method = '_render'.ucfirst($part);
			if(method_exists($this, $method)) {
				$sql = $this->$method($sql);
			}
		}
		return $sql;
	}
	
	public function removePart($part) {
		unset($this->_parts[$part]);
		return $this;
	}
	
	public function reset($part = null) {
		if($part==null) {
			$this->_parts = self::$_partsInit;
		} else 
			if(array_key_exists($part, self::$_partsInit)) {
				$this->_parts[$part] = self::$_partsInit[$part];
			}
		return $this;
	}
	
	public function getAdapter() {
		return $this->_adapter;
	}
	public function setAdapter($adapter) {
		$this->_adapter = $adapter;
		return $this;
	}
	
	protected function _join($type, $name, $cond, $cols, $schema = null) {
		if(!in_array($type, self::$_joinTypes)&&$type!=self::FROM) {
			throw new Exception("Invalid join type '$type'");
		}
		
		if(count($this->_parts[self::UNION])) {
			throw new system_db_select_exception("Invalid use of table with ".self::SQL_UNION);
		}
		
		if(empty($name)) {
			$correlationName = $tableName = '';
		} else 
			if(is_array($name)) {
				// Must be array($correlationName => $tableName) or array($ident, ...)
				foreach($name as $_correlationName => $_tableName) {
					if(is_string($_correlationName)) {
						// We assume the key is the correlation name and value is the table name
						$tableName = $_tableName;
						$correlationName = $_correlationName;
					} else {
						// We assume just an array of identifiers, with no correlation name
						$tableName = $_tableName;
						$correlationName = $this->_uniqueCorrelation($tableName);
					}
					break;
				}
			} else 
				if($name instanceof system_db_expr || $name instanceof system_db_select) {
					$tableName = $name;
					$correlationName = $this->_uniqueCorrelation('t');
				} else 
					if(preg_match('/^(.+)\s+AS\s+(.+)$/i', $name, $m)) {
						$tableName = $m[1];
						$correlationName = $m[2];
					} else {
						$tableName = $name;
						$correlationName = $this->_uniqueCorrelation($tableName);
					}
		
		// Schema from table name overrides schema argument
		if(!is_object($tableName)&&false!==strpos($tableName, '.')) {
			list($schema, $tableName) = explode('.', $tableName);
		}
		
		$lastFromCorrelationName = null;
		if(!empty($correlationName)) {
			if(array_key_exists($correlationName, $this->_parts[self::FROM])) {
				throw new system_db_select_exception("You cannot define a correlation name '$correlationName' more than once");
			}
			
			if($type==self::FROM) {
				// append this from after the last from joinType
				$tmpFromParts = $this->_parts[self::FROM];
				$this->_parts[self::FROM] = array();
				// move all the froms onto the stack
				while($tmpFromParts) {
					$currentCorrelationName = key($tmpFromParts);
					if($tmpFromParts[$currentCorrelationName]['joinType']!=self::FROM) {
						break;
					}
					$lastFromCorrelationName = $currentCorrelationName;
					$this->_parts[self::FROM][$currentCorrelationName] = array_shift($tmpFromParts);
				}
			} else {
				$tmpFromParts = array();
			}
			$this->_parts[self::FROM][$correlationName] = array('joinType' => $type, 'schema' => $schema, 'tableName' => $tableName, 'joinCondition' => $cond);
			while($tmpFromParts) {
				$currentCorrelationName = key($tmpFromParts);
				$this->_parts[self::FROM][$currentCorrelationName] = array_shift($tmpFromParts);
			}
		}
		
		// add to the columns from this joined table
		if($type==self::FROM&&$lastFromCorrelationName==null) {
			$lastFromCorrelationName = true;
		}
		
		$this->_tableCols($correlationName, $cols, $lastFromCorrelationName);
		
		return $this;
	}
	
	public function _joinUsing($type, $name, $cond, $cols = '*', $schema = null) {
		if(empty($this->_parts[self::FROM])) {
			throw new system_db_select_exception("You can only perform a joinUsing after specifying a FROM table");
		}
		
		$join = $this->_adapter->quoteIdentifier(key($this->_parts[self::FROM]), true);
		$from = $this->_adapter->quoteIdentifier($this->_uniqueCorrelation($name), true);
		
		$cond1 = $from.'.'.$cond;
		$cond2 = $join.'.'.$cond;
		$cond = $cond1.' = '.$cond2;
		
		return $this->_join($type, $name, $cond, $cols, $schema);
	}
	
	private function _uniqueCorrelation($name) {
		if(is_array($name)) {
			$c = end($name);
		} else {
			// Extract just the last name of a qualified table name
			$dot = strrpos($name, '.');
			$c = ($dot===false) ? $name : substr($name, $dot+1);
		}
		for($i = 2; array_key_exists($c, $this->_parts[self::FROM]); ++$i) {
			$c = $name.'_'.(string) $i;
		}
		return $c;
	}
	
	protected function _tableCols($correlationName, $cols, $afterCorrelationName = null) {
		if(!is_array($cols)) {
			$cols = array($cols);
		}
		
		if($correlationName==null) {
			$correlationName = '';
		}
		
		$columnValues = array();
		
		foreach(array_filter($cols) as $alias => $col) {
			$currentCorrelationName = $correlationName;
			if(is_string($col)) {
				// Check for a column matching "<column> AS <alias>" and extract the alias name
				if(preg_match('/^(.+)\s+'.self::SQL_AS.'\s+(.+)$/i', $col, $m)) {
					$col = $m[1];
					$alias = $m[2];
				}
				// Check for columns that look like functions and convert to system_db_expr
				if(preg_match('/\(.*\)/', $col)) {
					$col = new system_db_expr($col);
				} elseif(preg_match('/(.+)\.(.+)/', $col, $m)) {
					$currentCorrelationName = $m[1];
					$col = $m[2];
				}
			}
			$columnValues[] = array($currentCorrelationName, $col, is_string($alias) ? $alias : null);
		}
		
		if($columnValues) {
			
			// should we attempt to prepend or insert these values?
			if($afterCorrelationName===true||is_string($afterCorrelationName)) {
				$tmpColumns = $this->_parts[self::COLUMNS];
				$this->_parts[self::COLUMNS] = array();
			} else {
				$tmpColumns = array();
			}
			
			// find the correlation name to insert after
			if(is_string($afterCorrelationName)) {
				while($tmpColumns) {
					$this->_parts[self::COLUMNS][] = $currentColumn = array_shift($tmpColumns);
					if($currentColumn[0]==$afterCorrelationName) {
						break;
					}
				}
			}
			// apply current values to current stack
			foreach($columnValues as $columnValue) {
				array_push($this->_parts[self::COLUMNS], $columnValue);
			}
			
			// finish ensuring that all previous values are applied (if they exist)
			while($tmpColumns) {
				array_push($this->_parts[self::COLUMNS], array_shift($tmpColumns));
			}
		}
	}
	
	protected function _where($condition, $value = null, $type = null, $bool = true) {
		if(count($this->_parts[self::UNION])) {
			throw new system_db_select_exception("Invalid use of where clause with ".self::SQL_UNION);
		}
		
		if($value!==null) {
			$condition = $this->_adapter->quoteInto($condition, $value, $type);
		}
		$cond = "";
		if($this->_parts[self::WHERE]) {
			if($bool===true) {
				$cond = self::SQL_AND.' ';
			} else {
				$cond = self::SQL_OR.' ';
			}
		}
		
		return $cond."($condition)";
	}
	
	protected function _getQuotedSchema($schema = null) {
		if($schema===null) {
			return null;
		}
		return $this->_adapter->quoteIdentifier($schema, true).'.';
	}
	
	protected function _getQuotedTable($tableName, $correlationName = null) {
		return $this->_adapter->quoteTableAs($tableName, $correlationName, true);
	}
	
	protected function _renderDistinct($sql) {
		if($this->_parts[self::DISTINCT]) {
			$sql .= ' '.self::SQL_DISTINCT;
		}
		
		return $sql;
	}
	
	protected function _renderColumns($sql) {
		if(!count($this->_parts[self::COLUMNS])) {
			return null;
		}
		
		$columns = array();
		foreach($this->_parts[self::COLUMNS] as $columnEntry) {
			list($correlationName, $column, $alias) = $columnEntry;
			if($column instanceof system_db_expr) {
				$columns[] = $this->_adapter->quoteColumnAs($column, $alias, true);
			} else {
				if($column==self::SQL_WILDCARD) {
					$column = new system_db_expr(self::SQL_WILDCARD);
					$alias = null;
				}
				if(empty($correlationName)) {
					$columns[] = $this->_adapter->quoteColumnAs($column, $alias, true);
				} else {
					$columns[] = $this->_adapter->quoteColumnAs(array($correlationName, $column), $alias, true);
				}
			}
		}
		
		return $sql .= ' '.implode(', ', $columns);
	}
	
	public function _getDummyTable() {
		return array();
	}
	
	protected function _renderFrom($sql) {
		if(empty($this->_parts[self::FROM])) {
			$this->_parts[self::FROM] = $this->_getDummyTable();
		}
		
		$from = array();
		
		foreach($this->_parts[self::FROM] as $correlationName => $table) {
			$tmp = '';
			
			$joinType = ($table['joinType']==self::FROM) ? self::INNER_JOIN : $table['joinType'];
			
			// Add join clause (if applicable)
			if(!empty($from)) {
				$tmp .= ' '.strtoupper($joinType).' ';
			}
			
			$tmp .= $this->_getQuotedSchema($table['schema']);
			//添加了一个表前缀
			$tmp .= $this->_getQuotedTable(system_db_table::getTablePrefix().$table['tableName'], $correlationName);
			
			// Add join conditions (if applicable)
			if(!empty($from)&&!empty($table['joinCondition'])) {
				$tmp .= ' '.self::SQL_ON.' '.$table['joinCondition'];
			}
			
			// Add the table name and condition add to the list
			$from[] = $tmp;
		}
		
		// Add the list of all joins
		if(!empty($from)) {
			$sql .= ' '.self::SQL_FROM.' '.implode("\n", $from);
		}
		
		return $sql;
	}
	
	protected function _renderUnion($sql) {
		if($this->_parts[self::UNION]) {
			$parts = count($this->_parts[self::UNION]);
			foreach($this->_parts[self::UNION] as $cnt => $union) {
				list($target, $type) = $union;
				if($target instanceof system_db_select) {
					$target = $target->assemble();
				}
				$sql .= $target;
				if($cnt<$parts-1) {
					$sql .= ' '.$type.' ';
				}
			}
		}
		
		return $sql;
	}
	
	protected function _renderWhere($sql) {
		if($this->_parts[self::FROM]&&$this->_parts[self::WHERE]) {
			$sql .= ' '.self::SQL_WHERE.' '.implode(' ', $this->_parts[self::WHERE]);
		}
		
		return $sql;
	}
	
	protected function _renderGroup($sql) {
		if($this->_parts[self::FROM]&&$this->_parts[self::GROUP]) {
			$group = array();
			foreach($this->_parts[self::GROUP] as $term) {
				$group[] = $this->_adapter->quoteIdentifier($term, true);
			}
			$sql .= ' '.self::SQL_GROUP_BY.' '.implode(",\n\t", $group);
		}
		
		return $sql;
	}
	
	protected function _renderHaving($sql) {
		if($this->_parts[self::FROM]&&$this->_parts[self::HAVING]) {
			$sql .= ' '.self::SQL_HAVING.' '.implode(' ', $this->_parts[self::HAVING]);
		}
		
		return $sql;
	}
	
	protected function _renderOrder($sql) {
		if($this->_parts[self::ORDER]) {
			$order = array();
			foreach($this->_parts[self::ORDER] as $term) {
				if(is_array($term)) {
					if(is_numeric($term[0])&&strval(intval($term[0]))==$term[0]) {
						$order[] = (int) trim($term[0]).' '.$term[1];
					} else {
						$order[] = $this->_adapter->quoteIdentifier($term[0], true).' '.$term[1];
					}
				} else 
					if(is_numeric($term)&&strval(intval($term))==$term) {
						$order[] = (int) trim($term);
					} else {
						$order[] = $this->_adapter->quoteIdentifier($term, true);
					}
			}
			$sql .= ' '.self::SQL_ORDER_BY.' '.implode(', ', $order);
		}
		
		return $sql;
	}
	
	protected function _renderLimitoffset($sql) {
		$count = 0;
		$offset = 0;
		
		if(!empty($this->_parts[self::LIMIT_OFFSET])) {
			$offset = (int) $this->_parts[self::LIMIT_OFFSET];
			$count = PHP_INT_MAX;
		}
		
		if(!empty($this->_parts[self::LIMIT_COUNT])) {
			$count = (int) $this->_parts[self::LIMIT_COUNT];
		}
		
		/*
         * Add limits clause
         */
		if($count>0) {
			$sql = trim($this->_adapter->limit($sql, $count, $offset));
		}
		
		return $sql;
	}
	
	protected function _renderForupdate($sql) {
		if($this->_parts[self::FOR_UPDATE]) {
			$sql .= ' '.self::SQL_FOR_UPDATE;
		}
		
		return $sql;
	}
	
	public function __call($method, array $args) {
		$matches = array();
		
		/**
		 * Recognize methods for Has-Many cases:
		 * findParent<Class>()
		 * findParent<Class>By<Rule>()
		 * Use the non-greedy pattern repeat modifier e.g. \w+?
		 */
		if(preg_match('/^join([a-zA-Z]*?)Using$/', $method, $matches)) {
			$type = strtolower($matches[1]);
			if($type) {
				$type .= ' join';
				if(!in_array($type, self::$_joinTypes)) {
					throw new system_db_select_exception("Unrecognized method '$method()'");
				}
				if(in_array($type, array(self::CROSS_JOIN, self::NATURAL_JOIN))) {
					throw new system_db_select_exception("Cannot perform a joinUsing with method '$method()'");
				}
			} else {
				$type = self::INNER_JOIN;
			}
			array_unshift($args, $type);
			return call_user_func_array(array($this, '_joinUsing'), $args);
		}
		
		throw new system_db_select_exception("Unrecognized method '$method()'");
	}
	
	/**
	 * Implements magic method.
	 *
	 * @return string This object as a SELECT string.
	 */
	public function __toString() {
		try {
			$sql = $this->assemble();
		} catch (Exception $e) {
			trigger_error($e->getMessage(), E_USER_WARNING);
			$sql = '';
		}
		return (string) $sql;
	}
	
	public function fetchAll() {
		return $this->query()->fetchAll($this);
	}
	public function fetchRow() {
		return $this->query()->fetchRow($this);
	}
	
	public function fetchCount() {
		return $this->query()->fetchOne($this->getCountSelect());
	}
	
	const ROW_COUNT_COLUMN = 'system_row_count';
	
	public function getCountSelect() {
		$rowCount = clone $this;
		//$rowCount->__toString();
		//remove limit 
		$rowCount->removePart(self::LIMIT_COUNT)->removePart(self::LIMIT_OFFSET);
		
		$db = $rowCount->getAdapter();
		
		$countColumn = $db->quoteIdentifier($db->foldCase(self::ROW_COUNT_COLUMN));
		$countPart = 'COUNT(1) AS ';
		$groupPart = null;
		$unionParts = $rowCount->getPart(self::UNION);
		
		/**
		 * If we're dealing with a UNION query, execute the UNION as a subquery
		 * to the COUNT query.
		 */
		if(!empty($unionParts)) {
			$expression = new system_db_expr($countPart.$countColumn);
			
			$rowCount = $db->select()->bind($rowCount->getBind())->from($rowCount, $expression);
		} else {
			$columnParts = $rowCount->getPart(self::COLUMNS);
			$groupParts = $rowCount->getPart(self::GROUP);
			$havingParts = $rowCount->getPart(self::HAVING);
			$isDistinct = $rowCount->getPart(self::DISTINCT);
			
			/**
			 * If there is more than one column AND it's a DISTINCT query, more
			 * than one group, or if the query has a HAVING clause, then take
			 * the original query and use it as a subquery os the COUNT query.
			 */
			if(($isDistinct&&count($columnParts)>1)||count($groupParts)>1||!empty($havingParts)) {
				$rowCount->reset(self::ORDER);
				$rowCount = $db->select()->bind($rowCount->getBind())->from($rowCount);
			} else 
				if($isDistinct) {
					$part = $columnParts[0];
					
					if($part[1]!==self::SQL_WILDCARD && !($part[1] instanceof system_db_expr)) {
						$column = $db->quoteIdentifier($part[1], true);
						
						if(!empty($part[0])) {
							$column = $db->quoteIdentifier($part[0], true).'.'.$column;
						}
						
						$groupPart = $column;
					}
				} else 
					if(!empty($groupParts)) {
						$groupPart = $db->quoteIdentifier($groupParts[0], true);
					}
			
			/**
			 * If the original query had a GROUP BY or a DISTINCT part and only
			 * one column was specified, create a COUNT(DISTINCT ) query instead
			 * of a regular COUNT query.
			 */
			if(!empty($groupPart)) {
				$countPart = 'COUNT(DISTINCT '.$groupPart.') AS ';
			}
			
			/**
			 * Create the COUNT part of the query
			 */
			$expression = new system_db_expr($countPart.$countColumn);
			
			$rowCount->reset(self::COLUMNS)->reset(self::ORDER)->reset(self::LIMIT_OFFSET)->reset(self::GROUP)->reset(self::DISTINCT)->reset(self::HAVING)->columns($expression);
		}
		$rowCount->reset(self::LIMIT_OFFSET);
		$rowCount->reset(self::LIMIT_OFFSET);
		return $rowCount;
	}
}